function WSSHClient() {
};
WSSHClient.prototype._generateEndpoint = function () {
    var endpoint = "ws://" + sessionStorage.getItem('hostName') + "/webssh";
    return endpoint;
};

WSSHClient.prototype.connect = function (options) {
    var endpoint = this._generateEndpoint();
    console.log("endpoint" + endpoint)
    if (window.WebSocket) {
        //如果支持websocket
        this._connection = new WebSocket(endpoint);
    } else {
        //否则报错
        options.onError('WebSocket Not Supported');
        return;
    }

    this._connection.onopen = function () {
        options.onConnect();
    };

    this._connection.onmessage = function (evt) {
        var data = evt.data.toString();
        //data = base64.decode(data);
        options.onData(data);
    };


    this._connection.onclose = function (evt) {
        options.onClose();
    };
};

WSSHClient.prototype.send = function (data) {
    this._connection.send(JSON.stringify(data));
};

WSSHClient.prototype.sendInitData = function (options) {
    //连接参数
    this._connection.send(JSON.stringify(options));
}

WSSHClient.prototype.sendClientData = function (data) {
    //发送指令
    this._connection.send(JSON.stringify({"operate": "command", "command": data}))
}

var client = new WSSHClient();
layui.use(['table', 'form', 'element', 'upload','util'], function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        util = layui.util,
        upload = layui.upload,
        element = layui.element;
    let receive = window.opener["sshParams"];
    //获取接收到的数据
    let ip = receive["ip"];
    let username = receive["username"];
    table.render({
        elem: '#serverFile'
        , url: '/server/queryFileByPath'
        , toolbar: '#toolbarTable'
        , title: '文件'
        , totalRow: true
        , skin: 'line'
        , where: {
            ip: ip,
            path: $("#pathName").val() == undefined ? "/" + username : $("#pathName").val(),
            name: $("#name").val() == undefined ? "": $("#name").val(),
        }
        , id: "serverFile"
        , cols: [[
            {checkbox: true, fixed: true}
            , {
                field: 'fileName', title: '文件名', width: 400, sort: true,edit: 'text',  event: 'clickEvent', templet: function (d) {
                    let className = "iconfont icon-wenjianjia";
                    if (d.dir == 0) {
                        className = "iconfont icon-24gl-fileText"
                    }
                    return '<i class= "' + className + '">' + d.fileName + '</i>'
                }
            }
            , {event: 'clickEvent', field: 'fileSize', title: '大小', width: 200, sort: true}
            , {event: 'clickEvent', field: 'fileType', title: '类型', width: 200, sort: true}
            , {event: 'clickEvent', field: 'updateTime', title: '修改时间', width: 200, sort: true}
            , {event: 'clickEvent', field: 'permissionsString', title: '权限', width: 200, sort: true}
            , {event: 'clickEvent', field: 'user', title: '账户', width: 200, sort: true}
            , {event: 'clickEvent', fixed: 'right', title: '操作', toolbar: '#barDemo', width: 350}
        ]]
        , even: true
        , width: 1900
        , height: 370
        // , height: 'full-150'
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data //解析数据列表
            };
        }
        , done: function (res, currentCount) {
            $('#serverFile').next().find('.layui-table-body').find("table").find("tbody").children("tr").on('dblclick', function () {
                var id = JSON.stringify($('#serverFile').next().find('.layui-table-body').find("table").find("tbody").find(".layui-table-hover").data('index'));
                var obj = res.data[id];
                clickEvent(obj)
            });
            if (!$("#pathName").val()) {
                $("#pathName").val("/" + username)
            }
        }
    });
    //监听单元格编辑
    table.on('edit(serverFile)', function(obj){
        const value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        const old = data.filePath.replace($("#pathName").val()+"/","")
        layer.msg(old + ' 更改为：'+ util.escape(value));
        const oldname = data.filePath
        const newname = $("#pathName").val()+"/"+util.escape(value)
        const params = {
            ip:ip,
            oldFileName:oldname,
            newFileName:newname,
        }
        $.ajax({
            url: '/server/reNameServerFile',
            data: JSON.stringify(params),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            type: "PUT",
            success: function (result) {

            }
        })
    });

    //头工具栏事件
    table.on('toolbar(serverFile)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        switch (obj.event) {
            case 'add':
                add();
                break;
            case 'uploadFile':
                uploadFile();
                break;
            case 'del':
                if (data.length == 0) {
                    layer.msg("请先勾选数据", {icon: 2, time: 3000});
                    return;
                }
                let array2 = [];
                for (let i = 0; i < data.length; i++) {
                    const downloadData = {
                        filePath: data[i].filePath,
                        ip: ip,
                        dir: data[i].dir,
                        fileName: data[i].fileName,
                    }
                    array2.push(downloadData)
                }
                del(array2);
                break;
            case 'download':
                if (data.length == 0) {
                    layer.msg("请先勾选数据", {icon: 2, time: 3000});
                    return;
                }
                for (let i = 0; i < data.length; i++) {
                    download(data[i].filePath);
                }
                break;
        }
        ;
    });

    $("#pathName").bind('blur change',function(){
        search()
    })
    function add() {
        const pathName = $("#pathName").val()
        layer.open({
            type: 2,
            title: '新增文件',
            area: ['500px', '400px'],
            fix: false, //
            shade: 0,
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["addFile.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find("#filePath").val(pathName);
                body.find("#filePath").html(pathName);
                body.find("#ip").val(ip);
                body.find("#ip").html(ip);
            },
            yes: function () {
            }
        });
    }
    function uploadFile() {
        const pathName = $("#pathName").val()
        layer.open({
            type: 2,
            title: '上传文件',
            area: ['800px', '600px'],
            fix: false, //
            shade: 0,
            closeBtn: true,
            shift: 2,
            shadeClose: true,
            content: ["uploadFile.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find("#filePath").val(pathName);
                body.find("#filePath").html(pathName);
                body.find("#ip").val(ip);
                body.find("#ip").html(ip);
            },
            yes: function () {
            }
        });
    }

    //监听行工具事件
    table.on('tool(serverFile)', function (obj) {
        const data = obj.data;
        if (obj.event === 'update') {
            update(data);
        } else if (obj.event === 'del') {
            let array2 = [];
            const downloadData = {
                filePath: data.filePath,
                ip: ip,
                dir: data.dir,
                fileName: data.fileName,
            }
            array2.push(downloadData)
            del(array2)
        } else if (obj.event === 'ssh') {
            ssh(data)
        }
    });
    function download(path) {
        const load = layer.load()
        const url = '/server/download/';
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'get');
        const data = {
            ip: ip,
            path: path
        };
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
        layer.close(load);
    }

    function clickEvent(data) {
        //文件夹就进入，文件则下载到本地并打开
        const path = data.filePath
        if (data.dir == 1) {
            $("#pathName").val(path)
            search()
        } else {
            const params = {
                ip: ip,
                path: path
            }
            //记录打开状态
            const state = sessionStorage.getItem(ip + path)
            if (state) {
                return
            }
            sessionStorage.setItem(ip + path, "open");

            $.ajax({
                url: '/server/downloadForTemp',
                data: JSON.stringify(params),
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                type: "POST",
                success: function (result) {
                    const data = result.data;
                    layer.open({
                        type: 2,
                        title: '编辑文件',
                        area: ['1000px', '700px'],
                        fix: false, //
                        shade: 0,
                        closeBtn: false,
                        shift: 2,
                        shadeClose: false,
                        content: ["updateFile.html", 'no'],
                        success: function (layero, index) {
                            const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                            body.find("#fileName").html(data.fileName);
                            body.find("#content").html(data.content);
                            body.find("#linuxPath").html(data.linuxPath);
                            body.find("#linuxPath").val(data.linuxPath);
                            body.find("#path").val(data.path);
                            body.find("#originalFileName").val(data.originalFileName);
                            body.find("#ip").val(data.ip);
                        },
                        yes: function () {
                        }
                    });
                }
            })
            setTimeout(function () {
                sessionStorage.removeItem(ip + path)
            }, 5000)
        }
    }


    function del(params) {
        layer.confirm("确认要删除吗，删除后不能恢复", {title: "删除确认"}, function (index) {
            $.ajax({
                type: "POST",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/server/delServerFile/",//url
                data: JSON.stringify(params),
                contentType: "application/json;charset=utf-8",
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg("删除成功", {icon: 1, time: 1000}, function () {
                            search()
                        });
                    } else {
                        layer.msg(result.desc, {icon: 2, time: 3000}, function () {
                            search()
                        });
                    }
                    ;
                },
                error: function () {
                    alert("异常！");
                }
            });
        })
    }
    $('#pathName').bind('keydown', function (event) {
        var event = window.event || arguments.callee.caller.arguments[0];
        if (event.keyCode == 13){
            search()
        }
    });
    $('#name').bind('keydown', function (event) {
        var event = window.event || arguments.callee.caller.arguments[0];
        if (event.keyCode == 13){
            search()
        }
    });
    $('#refresh').click(function () {
        search();
    });
    $('#up').click(function () {
        var pathName = $('#pathName').val()
        if (pathName == "/") {
            return
        }
        pathName = getValue(pathName)
        if (pathName.endsWith("/") && pathName != "/") {
            pathName = pathName.substring(0, pathName.length - 1)
        }
        $('#pathName').val(pathName)
        search();
    });

    function getValue(url) {
        //如果不写这一行 将会取最后一个/前所有值
        //获取最后一个/的位置
        var site = url.lastIndexOf("/");
        //截取最后一个/后的值
        return url.substring(0, site + 1);
    }

    window.search =function () {
        //执行重载
        table.reloadData('serverFile', {
            method: 'get'
            , where: {
                ip: ip,
                path: $('#pathName').val(),
                name: $("#name").val(),
            }
        }, 'data');
    }

});